Array.prototype.myForeach = function (fn) {

    let that = this;

    for (let i = 0; i < that.length; i++) {
        fn.apply(that, that[i], i, that);

    }

}

// arr.forEach()

const arr = [1,2,3,4,5]
function getAjax(url){
    return new Promise(resolve=>{
        console.log(url)
        resolve(url)
    })
}  // return new Promise
// fn(arr, max)

class solution {
    constructor(max) {
        this.queue = [];
        this.curCnt = 0;
        this.maxCnt = max;
        this.result = [];
    }

    add(url, index) {
        this.queue.push([url, index]);
        // console.log(this.queue)
        this.run();
    }

    run() {
        if (this.curCnt < this.maxCnt && this.queue.length !== 0) {
            // console.log(this.queue)
            let temp = this.queue.shift();
            let curURL = temp[0];
            let curIndex = temp[1];
            // this.curCnt++;
            if (temp) {
                this.curCnt++;
                // let res = await getAjax(curURL);
                // this.result[curIndex] = res; // ？？顺序
                // this.curCnt--;
                // this.run();

                Promise.resolve(getAjax(curURL)).then(res => {
                    console.log("hhh", res);
                    this.result[curIndex] = res;
                    this.curCnt--;
                    this.run();
                })
                
               
                // let res = await getAjax(curURL);
                // this.result[curIndex] = res; // ？？顺序
                // this.curCnt--;
                // this.run();
                
            }
        }
    }

}


function fn(arr, max) {
    let sol = new solution(max);

    for (let i = 0; i < arr.length; i++) {
        //add 
        sol.add(arr[i], i);
    }
}

console.log("-------------",fn(arr,3))